from utils.json_res import json_response
from django.shortcuts import render, reverse, redirect
# Create your views here.
from django.views import View
from django.contrib.auth import logout,authenticate #导入登出和验证登录
from utils.res_code import Code
from . import forms
from .forms import LoginForm
from .models import MyUser

#注册
class Registe(View):
    def get(self,request):
        return render(request, 'register.html')
    def post(self,request):
        form = forms.CheckForm(request.POST) #校验from表单
        #判定
        if form.is_valid():
            username=form.data.get('username')
            email=form.data.get('email')
            password=form.data.get('password')
            MyUser.objects.create_user(username=username,password=password,email=email)

            return json_response(errmsg='恭喜你注册成功！')
        else:
            # 定义一个错误信息列表
            err_msg_list = []
            for item in form.errors.values():
                err_msg_list.append(item[0])
            err_msg_str = '/'.join(err_msg_list)

            return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)
#登录
class LoginView(View):
    """
    登录视图
    """
    def get(self,request):
        return render(request, 'login.html')
    def post(self,request):
        form = LoginForm(data=request.POST, request=request)
        if form.is_valid():
            return json_response(errmsg='恭喜登录成功！')
        else:
            err_msg_list = []
            for item in form.errors.values():
                err_msg_list.append(item[0])
            err_msg_str = '/'.join(err_msg_list)
            return json_response(errno=Code.PWDERR, errmsg=err_msg_str)

#登出
class LogoutView(View):
    def get(self,request):
        logout(request)
        return redirect(reverse('album:base'))

def check_username_view(request, username):
    #用户名
    # 去数据库查询数据,然后返回就好了
    data={
        'errno':'0',
        'errmsg':'ok',
        'data':{
            'username':username,    #用户名查询
            'count':MyUser.objects.filter(name=username).count()  #查询用户数  #
        }
    }
    return json_response(data=data)
def check_email_view(request,emails):
    #邮箱查询
    #去数据库查询
    data={
        'errno':'0',
        'errmsg':'ok',
        'data':{
            'username':emails,    #邮箱查询
            'count':MyUser.objects.filter(email=emails).count()  #查询邮箱数  #
        }
    }
    return json_response(data=data)